import matplotlib.pyplot as plt
from sklearn.neighbors import KNeighborsClassifier
import cv2 as cv
import pickle,os,shutil
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
#shutil.copy('X', 'test')
#shutil.copy('Y', 'test')
with open('X','rb') as f:
    X=pickle.load(f)
with open('Y','rb') as f:
    Y=pickle.load(f)
print(len(X))
print(len(Y))
X_train,X_test,y_train,y_test=train_test_split(X,Y,test_size=0.2)
# clf=RandomForestClassifier()
# clf.fit(X_train,y_train)
# acc=clf.score(X_test,y_test)
# print(acc)
a=[]
k=[]
for i in range(1,len(X_train)+1):
    knn = KNeighborsClassifier(n_neighbors=i)
    knn.fit(X_train, y_train)
    a.append(knn.score(X_test, y_test))
    k.append(i)
acc=max(a)
k=k[a.index(acc)]
knn = KNeighborsClassifier(n_neighbors=k)
knn.fit(X_train,y_train)
print(acc)
print(k)
# svc=SVC(kernel='rbf',C=1)
# svc.fit(X_train,y_train)
# print(svc.score(X_test,y_test))
img=cv.imread('ceshi.jpg')
#plt.imshow(img)
img_gray= cv.cvtColor(img, cv.COLOR_BGR2GRAY)
img_gray = cv.equalizeHist(img_gray) #对图像进行直方图增强
#1. 创建级联分类器
face_cascade = cv.CascadeClassifier()
# 2. 引入训练好的可用于人脸识别的级联分类器模型
face_cascade.load("haarcascade_frontalface_alt.xml")
# 3. 用此级联分类器识别图像中的所有人脸信息，返回一个包含有所有识别的人联系系的列表
# 列表中每一个元素包含四个值：面部左上角的坐标(x,y) 以及面部的宽和高(w,h)
faces = face_cascade.detectMultiScale(img_gray)

# 4. 为图像中的所有面部画框
for (x,y,w,h) in faces:
    cv.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
    face=img_gray[y:y+h,x:x+w]
    face = cv.resize(face, (32, 32))
    cv.putText(img,  # 要显示字体的图片
               f'{knn.predict([face.ravel()])}',  # 要显示的内容
               (x, y - 10),  # 要显示的位置
               cv.FONT_HERSHEY_SIMPLEX,  # 要使用的字体 -> 一般英文字体
               1,  # 字体放大倍数
               (0, 255, 0),  # 字体颜色
               2)  # 字体线条粗细
print(knn.predict([face.ravel()]))
plt.imshow(cv.cvtColor(img,cv.COLOR_BGR2RGB))
plt.text(0,0,round(acc,2))
plt.show()